/*城市选择*/
import React, { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useForm } from "../../context/metadata-context";
import { v4 as uuid } from "uuid";
import { getOriginField } from "../../utils";
//给iframe使用的city接口方法
let cityCtl = {};
var computeHeight = function (height, key) {
  if (cityCtl[key]) {
    cityCtl[key] && cityCtl[key].computeHeight(height);
  }
};
var getData = function (key) {
  if (!cityCtl[key]) return [];
  return cityCtl[key].getData();
};
var getParms = function (key) {
  if (!cityCtl[key]) return [];
  return cityCtl[key].getParms();
};
var setData = function (data, key) {
  if (cityCtl[key]) {
    cityCtl[key].setData(data);
    cityCtl[key].onChange();
  }
};
window.city = {
  computeHeight: computeHeight,
  getData: getData,
  getParms: getParms,
  setData: setData,
};

export default function CityDropdown({ field, value, onChange, onBlur, setOpen }) {
  const { params, urlPrefix } = useForm().root;
  //当前的唯一标识
  const cCodeRef = useRef(uuid());
  const iframeRef = useRef();
  const [, updater] = useState();
  //初始化时默认高度
  const heightRef = useRef(32);

  //组件销毁后释放内存
  useEffect(() => {
    return () => {
      delete cityCtl[cCodeRef.current];
    };
  }, []);

  useLayoutEffect(() => {
    iframeRef.current.contentWindow.code = cCodeRef.current;
    if (!cityCtl[cCodeRef.current]) {
      cityCtl[cCodeRef.current] = {
        //计算城市选择框高度
        computeHeight: function (h) {
          const maxHeight = 380;
          if (h > maxHeight) {
            heightRef.current = maxHeight;
          } else {
            heightRef.current = h || maxHeight;
          }
          updater({});
        },
        // 设置字段数据
        setData: function (data) {
          onChange(JSON.stringify(data));
          onBlur();
          setOpen(false);
        },
        // 获取字段数据
        getData: function () {
          var obj = {
            cityItem: JSON.parse(value || "[]"),
          };
          return obj;
        },
        // 获取传入参数
        getParms: function () {
          return {
            package_id: params.package_id,
            query_field: getOriginField(field),
            business_id: params.business_id,
          };
        },
      };
    }
  });

  return <iframe ref={iframeRef} id="cityiframe" frameBorder="0" width="100%" height={heightRef.current + "px"} src={urlPrefix + "/flowinstance/process/select-city"}></iframe>;
}
